import { mutation, query } from "./_generated/server";
import { Search } from "lucide-react";
import { v } from "convex/values";
// 查询满足特定条件的多条记录，并且如果没有找到符合条件的数据，它会抛出错误。这在确保查询结果完整性时非常有用，避免出现空数据的情况。
import { getAllOrThrow, getAll } from "convex-helpers/server/relationships";
import { GenericDatabaseReader } from "convex/server";

/**
 * 查询指定组织的所有信息。
 *
 * @param {Object} args - 查询参数。
 * @param {string} args.orgId - 组织的唯一标识符。
 * @returns {Promise<Array<Object>>} 包含看板信息的对象数组。
 */
export const get = query({
  args: {
    orgId: v.string(),
    search: v.optional(v.string()), // 可选参数
    favorites: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const identity = await ctx.auth.getUserIdentity();

    if (!identity) throw new Error("未经授权");

    const userId = identity.subject;

    // 查询收藏
    if (args.favorites) {
      // 有收藏的
      const favoritesBoards = await ctx.db
        .query("userFavorites")
        .withIndex("by_user_org", (q) =>
          q.eq("userId", userId).eq("orgId", args.orgId)
        )
        .order("desc")
        .collect();

      const ids = favoritesBoards.map((b) => b.boardId);

      const boards = ids.map(async (id) => {
        return ctx.db
          .query("boards")
          .withIndex("by_id", (q) => q.eq("_id", id))
          .order("desc")
          .unique()
          .then((board) => {
            return {
              ...board,
              isFavorite: true,
            };
          });
      });

      const favoritesBoardsBoolean = await Promise.all(boards);
      return favoritesBoardsBoolean;
    }

    const title = args.search as string;
    let boards = [];

    // 搜索查询
    if (title) {
      boards = await ctx.db
        .query("boards")
        .withSearchIndex("search_title", (q) =>
          q.search("title", title).eq("orgId", args.orgId)
        )
        .collect();
    } else {
      boards = await ctx.db
        .query("boards")
        .withIndex("by_org", (q) => q.eq("orgId", args.orgId)) // // 使用索引 `by_org` 来过滤指定 `orgId` 的数据。
        .order("desc")
        .collect();
    }

    // 带有收藏相关的项目
    const boardsWithFavoriteRelation = boards.map((board) => {
      return ctx.db
        .query("userFavorites")
        .withIndex("by_user_board", (q) =>
          q.eq("userId", identity.subject).eq("boardId", board._id)
        )
        .unique()
        .then((favorite) => {
          return {
            ...board,
            isFavorite: !!favorite,
          };
        });
    });

    const boardsWithFavoriteBoolean = Promise.all(boardsWithFavoriteRelation);
    return boardsWithFavoriteBoolean;
  },
});
